﻿using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Web.Script.Serialization;

namespace Communicate
{
    /// <summary>
    /// 序列化、反序列化类。
    /// </summary>
    internal class Serializer
    {
        ///  <summary>  
        ///  序列化为二进制字节数组  
        ///  </summary>  
        ///  <param  name="obj">要序列化的对象 </param>  
        ///  <returns>字节数组 </returns>  
        public static byte[] Serialize(object obj)
        {
            if (obj == null)
                return null;
            BinaryFormatter serializer = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, obj);
                return GZip.Compress(stream.GetBuffer());
            }
        }
        ///  <summary>  
        ///  从二进制数组反序列化得到对象  
        ///  </summary>  
        ///  <param  name="buf">字节数组 </param>  
        ///  <returns>得到的对象 </returns>  
        public static object Deserialize(byte[] buf)
        {
            if (buf == null || buf.Length == 0)
                return null;
            BinaryFormatter deserializer = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(GZip.Decompress(buf)))
            {
                stream.Seek(0, SeekOrigin.Begin);
                return deserializer.Deserialize(stream);
            }
        }
    }
    /// <summary>
    /// JSON序列化。
    /// </summary>
    internal class JsonSerializer
    {
        static JavaScriptSerializer jser = new JavaScriptSerializer() { MaxJsonLength = 1000000 };
        public static string Serialize(object obj)
        {
            return jser.Serialize(obj);
        }
        public static object Deserialize(string json, Type type)
        {
            return jser.Deserialize(json, type);
        }
    }
}
